package com.liumuxian.user.web.controller;

import com.liumuxian.user.pojo.User;
import com.liumuxian.user.service.UserService;
import com.liumuxian.user.wx.WeixinLoginParams;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public Result login(@RequestBody WeixinLoginParams params){
        User user= userService.login(params.getCode(),params.getEncryptedData(),params.getIv());
        if(user==null){
            return new Result(false, StatusCode.LOGINERROE, "登录失败");
        }
        //使得前后端可以通话的操作。采用JWT来实现。
        //生成令牌
        String token = jwtUtil.createJWT(user.getId(), user.getNickname(), "user");
        Claims claims = jwtUtil.parseJWT(token);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("role", "user");
        map.put("userInfo",user);
        map.put("expireTime",claims.getExpiration().getTime());
        return new Result(true, StatusCode.OK, "登录成功", map);
    }
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        userService.save(user);
        return new Result(true, StatusCode.OK,"保存成功！");
    }
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        userService.update(user);
        return new Result(true, StatusCode.OK,"修改成功！");
    }
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable String id){
        userService.delete(id);
        return new Result(true, StatusCode.OK,"删除成功！");
    }
    @GetMapping("/list")
    public Result findAllGesTate(){
        List<User> userList = userService.findAllGesTate(null,null,0);
        return new Result(true, StatusCode.OK,"查询成功！",userList);
    }
    @GetMapping("/{id}")
    public Result findById(@PathVariable String id){
        User userList = userService.findById(id);
        return new Result(true, StatusCode.OK,"查询成功！",userList);
    }

}
